package com.xujie.property_warranty_system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujie.property_warranty_system.dto.*;
import com.xujie.property_warranty_system.entity.User;
import com.xujie.property_warranty_system.entity.Role;
import com.xujie.property_warranty_system.enums.UserStatus;
import com.xujie.property_warranty_system.mapper.UserMapper;
import com.xujie.property_warranty_system.mapper.RoleMapper;
import com.xujie.property_warranty_system.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户服务类
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户注册
     */
    public String register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        QueryWrapper<User> usernameQuery = new QueryWrapper<>();
        usernameQuery.eq("username", registerDTO.getUsername());
        if (userMapper.selectOne(usernameQuery) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查手机号是否已存在
        QueryWrapper<User> phoneQuery = new QueryWrapper<>();
        phoneQuery.eq("phone", registerDTO.getPhone());
        if (userMapper.selectOne(phoneQuery) != null) {
            throw new RuntimeException("手机号已被注册");
        }
        
        // 检查身份证号是否已存在
        QueryWrapper<User> idCardQuery = new QueryWrapper<>();
        idCardQuery.eq("id_card", registerDTO.getIdCard());
        if (userMapper.selectOne(idCardQuery) != null) {
            throw new RuntimeException("身份证号已被注册");
        }
        
        // 创建用户对象
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        
        // 设置角色ID
        user.setRoleId(registerDTO.getRoleId());
        
        // 设置初始状态为待审核
        user.setUserStatus(UserStatus.PENDING);
        
        // 保存用户
        userMapper.insert(user);
        
        return "注册成功，等待管理员审核";
    }
    
    /**
     * 用户登录
     */
    public String login(UserLoginDTO loginDTO) {
        // 查找用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginDTO.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getUserStatus() == UserStatus.PENDING) {
            throw new RuntimeException("账户正在审核中，请耐心等待");
        }
        
        if (user.getUserStatus() == UserStatus.REJECTED) {
            throw new RuntimeException("账户审核未通过，请联系管理员");
        }
        
        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(user);
        
        // 获取用户角色信息
        Role role = roleMapper.selectById(user.getRoleId());
        String roleCode = role != null ? role.getRoleCode() : "OWNER";
        
        // 生成JWT token
        return jwtUtil.generateToken(user.getUsername(), user.getId(), roleCode);
    }
    
    /**
     * 获取待审核用户列表
     */
    public List<User> getPendingUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", UserStatus.PENDING.getCode());
        queryWrapper.orderByDesc("create_time");
        return userMapper.selectList(queryWrapper);
    }
    
    /**
     * 审核用户
     */
    public String auditUser(AuditUserDTO auditDTO) {
        User user = userMapper.selectById(auditDTO.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getUserStatus() != UserStatus.PENDING) {
            throw new RuntimeException("该用户已审核过");
        }
        
        // 更新用户状态
        user.setUserStatus(UserStatus.fromCode(auditDTO.getStatus()));
        user.setAuditRemark(auditDTO.getAuditRemark());
        user.setAuditTime(LocalDateTime.now());
        
        userMapper.updateById(user);
        
        String statusText = UserStatus.fromCode(auditDTO.getStatus()).getDescription();
        return "用户审核" + statusText + "成功";
    }
    
    /**
     * 根据用户名获取用户信息
     */
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }
    
    /**
     * 获取当前用户信息（包含角色信息）
     */
    public CurrentUserVO getCurrentUserInfo(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        
        if (user == null) {
            return null;
        }
        
        // 获取角色信息
        Role role = roleMapper.selectById(user.getRoleId());
        
        // 构建用户信息VO
        CurrentUserVO userInfo = new CurrentUserVO();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRealName(user.getRealName());
        userInfo.setPhone(user.getPhone());
        userInfo.setIdCard(user.getIdCard());
        userInfo.setHouseAddress(user.getHouseAddress());
        userInfo.setHouseArea(user.getHouseArea());
        userInfo.setHouseType(user.getHouseType());
        userInfo.setUserStatus(user.getUserStatus());
        userInfo.setAuditRemark(user.getAuditRemark());
        userInfo.setCreateTime(user.getCreateTime());
        userInfo.setLastLoginTime(user.getLastLoginTime());
        
        if (role != null) {
            userInfo.setRoleId(role.getId());
            userInfo.setRoleName(role.getRoleName());
            userInfo.setRoleCode(role.getRoleCode());
            userInfo.setRoleDescription(role.getDescription());
        }
        
        return userInfo;
    }
    
    /**
     * 获取所有用户列表
     */
    public List<User> getAllUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        return userMapper.selectList(queryWrapper);
    }
    
    /**
     * 更新用户信息
     */
    public String updateUserProfile(String username, UserUpdateDTO updateDTO) {
        User user = getUserByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查手机号是否被其他用户使用
        if (!user.getPhone().equals(updateDTO.getPhone())) {
            QueryWrapper<User> phoneQuery = new QueryWrapper<>();
            phoneQuery.eq("phone", updateDTO.getPhone());
            phoneQuery.ne("id", user.getId());
            if (userMapper.selectOne(phoneQuery) != null) {
                throw new RuntimeException("手机号已被其他用户使用");
            }
        }
        
        // 检查身份证号是否被其他用户使用
        if (!user.getIdCard().equals(updateDTO.getIdCard())) {
            QueryWrapper<User> idCardQuery = new QueryWrapper<>();
            idCardQuery.eq("id_card", updateDTO.getIdCard());
            idCardQuery.ne("id", user.getId());
            if (userMapper.selectOne(idCardQuery) != null) {
                throw new RuntimeException("身份证号已被其他用户使用");
            }
        }
        
        // 更新用户信息
        user.setRealName(updateDTO.getRealName());
        user.setPhone(updateDTO.getPhone());
        user.setIdCard(updateDTO.getIdCard());
        user.setHouseAddress(updateDTO.getHouseAddress());
        user.setHouseArea(updateDTO.getHouseArea());
        user.setHouseType(updateDTO.getHouseType());
        
        userMapper.updateById(user);
        
        return "用户信息更新成功";
    }
    
    /**
     * 修改密码
     */
    public String changePassword(String username, PasswordChangeDTO passwordDTO) {
        User user = getUserByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证当前密码
        if (!passwordEncoder.matches(passwordDTO.getCurrentPassword(), user.getPassword())) {
            throw new RuntimeException("当前密码不正确");
        }
        
        // 检查新密码是否与当前密码相同
        if (passwordEncoder.matches(passwordDTO.getNewPassword(), user.getPassword())) {
            throw new RuntimeException("新密码不能与当前密码相同");
        }
        
        // 更新密码
        user.setPassword(passwordEncoder.encode(passwordDTO.getNewPassword()));
        userMapper.updateById(user);
        
        return "密码修改成功";
    }
    
    /**
     * 分页查询用户列表
     */
    public PageResult<UserVO> getUserPage(UserPageDTO pageDTO) {
        // 创建分页对象
        Page<User> page = new Page<>(pageDTO.getPage(), pageDTO.getSize());
        
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(pageDTO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like("username", pageDTO.getKeyword())
                .or().like("real_name", pageDTO.getKeyword())
                .or().like("phone", pageDTO.getKeyword())
            );
        }
        
        // 状态筛选
        if (pageDTO.getStatus() != null) {
            queryWrapper.eq("status", pageDTO.getStatus());
        }
        
        // 角色筛选
        if (pageDTO.getRoleId() != null) {
            queryWrapper.eq("role_id", pageDTO.getRoleId());
        }
        
        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");
        
        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(page, queryWrapper);
        
        // 获取所有角色信息，用于映射角色名称
        List<Role> allRoles = roleMapper.selectList(null);
        Map<Long, String> roleMap = allRoles.stream()
            .collect(Collectors.toMap(Role::getId, Role::getRoleName));
        
        // 转换为VO对象
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVO.setRoleName(roleMap.get(user.getRoleId()));
            return userVO;
        }).collect(Collectors.toList());
        
        return new PageResult<>(
            userVOList,
            userPage.getTotal(),
            (int) userPage.getCurrent(),
            (int) userPage.getSize()
        );
    }
    
    /**
     * 获取用户统计信息
     */
    public UserStatsDTO getUserStats() {
        // 查询总用户数
        Long total = userMapper.selectCount(null);
        
        // 查询待审核用户数
        QueryWrapper<User> pendingQuery = new QueryWrapper<>();
        pendingQuery.eq("status", UserStatus.PENDING.getCode());
        Long pending = userMapper.selectCount(pendingQuery);
        
        // 查询已通过用户数
        QueryWrapper<User> approvedQuery = new QueryWrapper<>();
        approvedQuery.eq("status", UserStatus.APPROVED.getCode());
        Long approved = userMapper.selectCount(approvedQuery);
        
        // 查询已拒绝用户数
        QueryWrapper<User> rejectedQuery = new QueryWrapper<>();
        rejectedQuery.eq("status", UserStatus.REJECTED.getCode());
        Long rejected = userMapper.selectCount(rejectedQuery);
        
        return new UserStatsDTO(total, pending, approved, rejected);
    }
    
    /**
     * 审核通过用户
     */
    public String approveUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getStatus() != UserStatus.PENDING.getCode()) {
            throw new RuntimeException("该用户已审核过");
        }
        
        user.setStatus(UserStatus.APPROVED.getCode());
        user.setAuditTime(LocalDateTime.now());
        user.setAuditRemark("审核通过");
        
        userMapper.updateById(user);
        return "用户审核通过";
    }
    
    /**
     * 拒绝用户申请
     */
    public String rejectUser(Long userId, String reason) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (user.getStatus() != UserStatus.PENDING.getCode()) {
            throw new RuntimeException("该用户已审核过");
        }
        
        user.setStatus(UserStatus.REJECTED.getCode());
        user.setAuditTime(LocalDateTime.now());
        user.setAuditRemark(reason);
        
        userMapper.updateById(user);
        return "用户申请已拒绝";
    }
    
    /**
     * 管理员更新用户信息
     */
    public String updateUserByAdmin(Long userId, AdminUserUpdateDTO updateDTO) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查手机号是否被其他用户使用
        if (!user.getPhone().equals(updateDTO.getPhone())) {
            QueryWrapper<User> phoneQuery = new QueryWrapper<>();
            phoneQuery.eq("phone", updateDTO.getPhone());
            phoneQuery.ne("id", userId);
            if (userMapper.selectOne(phoneQuery) != null) {
                throw new RuntimeException("手机号已被其他用户使用");
            }
        }
        
        // 检查身份证号是否被其他用户使用
        if (StringUtils.hasText(updateDTO.getIdCard()) && !updateDTO.getIdCard().equals(user.getIdCard())) {
            QueryWrapper<User> idCardQuery = new QueryWrapper<>();
            idCardQuery.eq("id_card", updateDTO.getIdCard());
            idCardQuery.ne("id", userId);
            if (userMapper.selectOne(idCardQuery) != null) {
                throw new RuntimeException("身份证号已被其他用户使用");
            }
        }
        
        // 更新用户信息
        user.setRealName(updateDTO.getRealName());
        user.setPhone(updateDTO.getPhone());
        user.setIdCard(updateDTO.getIdCard());
        user.setHouseAddress(updateDTO.getHouseAddress());
        user.setHouseArea(updateDTO.getHouseArea());
        user.setHouseType(updateDTO.getHouseType());
        user.setStatus(updateDTO.getStatus());
        
        userMapper.updateById(user);
        return "用户信息更新成功";
    }
    
    /**
     * 重置用户密码
     */
    public String resetUserPassword(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 重置密码为123456
        user.setPassword(passwordEncoder.encode("123456"));
        userMapper.updateById(user);
        
        return "密码重置成功，新密码为：123456";
    }
    
    /**
     * 删除用户
     */
    public String deleteUser(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 不允许删除管理员用户
        if ("admin".equals(user.getUsername())) {
            throw new RuntimeException("不能删除管理员用户");
        }
        
        userMapper.deleteById(userId);
        return "用户删除成功";
    }
    
    /**
     * 获取用户详细信息
     */
    public UserVO getUserDetail(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        // 获取角色名称
        Role role = roleMapper.selectById(user.getRoleId());
        if (role != null) {
            userVO.setRoleName(role.getRoleName());
        }
        
        return userVO;
    }
}